package gui.panel_new.evaluation.student;

import enums.TextBundleEnum;
import enums.URLEnum;
import gui.other.JComponentCellRenderer;
import gui.panel_new.evaluation.exeptions.ExerciseNotBuiltException;
import gui.panel_new.evaluation.exeptions.PunctuationZeroException;
import j_util.Utiles;
import misc.BundlesProvider;
import model.TruthTable;
import model.eval.TestExcercise;
import model.eval.TestTruthTable;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
/*

    This file is part of Logica-Logike.

    Logica-Logike is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation version 3 of the License.

    Logica-Logike is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Logica-Logike.  If not, see <http://www.gnu.org/licenses/>.

 */
/**
 * @author Jose Martin Rozanec;
 */
public class TruthTableEvaluationPanel extends ExercisePanel {

    private javax.swing.JButton resetButton;

    private javax.swing.JPanel cuadroPanel;

    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JPanel operadoresPanel;
    private javax.swing.JTable table;

    private JLabel addsPoints;
    private JLabel substractPoints;
    private JTextField addsPointsField;
    private JTextField substractPointsField;

    private String parentesisOperando;
    private String operandoOperando;

    private List<String> tableTitles;
    private TruthTable truthTable;
    private String listSize0;
    private String input;

    private ResourceBundle textBundle;

    public TruthTableEvaluationPanel() {
        tableTitles = new ArrayList<String>();
        textBundle = BundlesProvider.getBundle(URLEnum.TEXT_BUNDLE);
        initComponents();
    }

    private void initComponents() {
        parentesisOperando = textBundle.getString(TextBundleEnum.WARNING_PARENTESIS_OPERANDO.toString()) + "!";
        operandoOperando = textBundle.getString(TextBundleEnum.WARNING_OPERANDO_OPERANDO.toString()) + "!";
        listSize0 = textBundle.getString(TextBundleEnum.WARNING_INICIO_OPERANDO.toString()) + "!";
        mainPanel = new javax.swing.JPanel();
        cuadroPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        operadoresPanel = new javax.swing.JPanel();
        jSeparator1 = new javax.swing.JSeparator();
        resetButton = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();

        addsPoints = new JLabel(textBundle.getString(TextBundleEnum.SUMA.toString()));
        substractPoints = new JLabel(textBundle.getString(TextBundleEnum.RESTA.toString()));
        addsPointsField = new JTextField(7);
        addsPointsField.setEditable(false);
        substractPointsField = new JTextField(7);
        substractPointsField.setEditable(false);

        mainPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
                new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true),
                textBundle.getString(TextBundleEnum.TABLA_VERDAD.toString())));

        cuadroPanel.setBackground(new java.awt.Color(255, 255, 255));
        cuadroPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
        jScrollPane1.setBorder(null);
        jScrollPane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        jScrollPane1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        table.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
                },
                new String[]{
                        "", "", "", ""
                }
        ));

        table.setForeground(Color.BLACK);
        table.setBackground(Color.WHITE);
        table.getTableHeader().setReorderingAllowed(false);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jScrollPane1.setViewportView(table);
        jScrollPane1.setPreferredSize(new Dimension(670, 585));//new Dimension(630, 500)//630
        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(
                BorderFactory.createEtchedBorder(),//new javax.swing.border.LineBorder(Color.BLACK, 1, true)
                textBundle.getString(TextBundleEnum.TABLA_VERDAD.toString())));


        jSeparator1.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator1.setOrientation(JSeparator.HORIZONTAL);
        jSeparator1.setPreferredSize(new Dimension(650, 10));

        resetButton.setText(textBundle.getString(TextBundleEnum.RESETEAR_EJERCICIO.toString()));
        resetButton.setMnemonic('v');
        resetButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                resetearButtonActionPerformed();//todo modificar la accion! Debe devolver a la representacion original
            }
        });

        jSeparator2.setForeground(new java.awt.Color(0, 0, 0));

        setLayout(new GridBagLayout());
        operadoresPanel.setLayout(new GridBagLayout());
//        operadoresPanel.setBorder();
        Dimension buttonsDimension = new Dimension(155, 25);
        resetButton.setPreferredSize(buttonsDimension);
        setBackground(Color.WHITE);

        JPanel scoringPanel = createScoringPanel();
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        int gridx = 0;
        int gridy = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridwidth = 1;
        scoringPanel.add(new JLabel(Utiles.createImageIcon(URLEnum.getReference(URLEnum.SEPARATOR_110))), gridBagConstraints);
        gridBagConstraints.gridx = 5;
        scoringPanel.add(new JLabel(Utiles.createImageIcon(URLEnum.getReference(URLEnum.SEPARATOR_110))), gridBagConstraints);
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridwidth = 1;
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        scoringPanel.add(resetButton, gridBagConstraints);
        gridBagConstraints.insets = new Insets(0, 0, 0, 0);

        operadoresPanel.add(scoringPanel);

        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 4;
        add(jScrollPane1, gridBagConstraints);
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridheight = 2;
        add(operadoresPanel, gridBagConstraints);
    }

    private void negacionButtonActionPerformed() {
        if (tableTitles.size() != 0) {
            char[] array = tableTitles.get(tableTitles.size() - 1).toCharArray();
            if (array[array.length - 1] == '(') {
                if (tableTitles.size() == 1) {
                    tableTitles.remove(0);
                    tableTitles.add(0, "(0");
                } else {
                    tableTitles.add("0");
                }
                addTableColumn(null);
            } else {
                if (checkIsNumber(tableTitles.get(tableTitles.size() - 1))) {
                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                            operandoOperando, "",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    tableTitles.add("0");
                    addTableColumn(null);
                }
            }
        } else {
            tableTitles.add("0");
            addTableColumn(null);
        }
    }

    private void conjuncionButtonActionPerformed() {
        if (tableTitles.size() == 0) {
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                    listSize0, "",
                    JOptionPane.WARNING_MESSAGE);
        } else {
            char[] array = tableTitles.get(tableTitles.size() - 1).toCharArray();
            if (array[array.length - 1] == '(') {
                JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                        parentesisOperando, "",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                if (checkIsNumber(tableTitles.get(tableTitles.size() - 1))) {
                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                            operandoOperando, "",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    tableTitles.add("7");
                    addTableColumn(null);
                }
            }
        }
    }

    private void disyuncionInclusivaButtonActionPerformed() {
        if (tableTitles.size() == 0) {
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                    listSize0, "",
                    JOptionPane.WARNING_MESSAGE);
        } else {
            char[] array = tableTitles.get(tableTitles.size() - 1).toCharArray();
            if (array[array.length - 1] == '(') {
                JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), parentesisOperando, "",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                if (checkIsNumber(tableTitles.get(tableTitles.size() - 1))) {
                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                            operandoOperando, "",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    tableTitles.add("5");
                    addTableColumn(null);
                }
            }
        }
    }

    private void disyuncionExclusivaButtonActionPerformed() {
        if (tableTitles.size() == 0) {
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                    listSize0, "",
                    JOptionPane.WARNING_MESSAGE);
        } else {
            char[] array = tableTitles.get(tableTitles.size() - 1).toCharArray();
            if (array[array.length - 1] == '(') {
                JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                        parentesisOperando, "",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                if (checkIsNumber(tableTitles.get(tableTitles.size() - 1))) {
                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                            operandoOperando, "",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    tableTitles.add("3");
                    addTableColumn(null);
                }
            }
        }
    }

    private void condicionalButtonActionPerformed() {
        if (tableTitles.size() == 0) {
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                    listSize0, "",
                    JOptionPane.WARNING_MESSAGE);
        } else {
            char[] array = tableTitles.get(tableTitles.size() - 1).toCharArray();
            if (array[array.length - 1] == '(') {
                JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                        parentesisOperando, "",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                if (checkIsNumber(tableTitles.get(tableTitles.size() - 1))) {
                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                            operandoOperando, "",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    tableTitles.add("1");
                    addTableColumn(null);
                }
            }
        }
    }

    private void bicondicionalButtonActionPerformed() {
        if (tableTitles.size() == 0) {
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                    listSize0, "",
                    JOptionPane.WARNING_MESSAGE);
        } else {
            char[] array = tableTitles.get(tableTitles.size() - 1).toCharArray();
            if (array[array.length - 1] == '(') {
                JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                        parentesisOperando, "",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                if (checkIsNumber(tableTitles.get(tableTitles.size() - 1))) {
                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                            operandoOperando, "",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    tableTitles.add("2");
                    addTableColumn(null);
                }
            }
        }
    }

    private void negacionConjuntaButtonActionPerformed() {
        if (tableTitles.size() == 0) {
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                    listSize0, "",
                    JOptionPane.WARNING_MESSAGE);
        } else {
            char[] array = tableTitles.get(tableTitles.size() - 1).toCharArray();
            if (array[array.length - 1] == '(') {
                JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), parentesisOperando, "",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                if (checkIsNumber(tableTitles.get(tableTitles.size() - 1))) {
                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                            operandoOperando, "",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    tableTitles.add("4");
                    addTableColumn(null);
                }
            }
        }
    }

    private void incompatibilidadButtonActionPerformed() {
        if (tableTitles.size() == 0) {
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                    listSize0, "",
                    JOptionPane.WARNING_MESSAGE);
        } else {
            char[] array = tableTitles.get(tableTitles.size() - 1).toCharArray();
            if (array[array.length - 1] == '(') {
                JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                        parentesisOperando, "",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                if (checkIsNumber(tableTitles.get(tableTitles.size() - 1))) {
                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                            operandoOperando, "",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    tableTitles.add("6");
                    addTableColumn(null);
                }
            }
        }
    }

    private void acceptButtonActionPerformed() {
//        input= inputTextField.getText(); //todo ver!
        if (input.equals("")) {
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                    textBundle.getString(TextBundleEnum.WARNING_VALORES_NULOS.toString()) + "!", "",
                    JOptionPane.WARNING_MESSAGE);
        } else {
            int first = (input.replace("(", "")).length();
            int second = (input.replace(")", "")).length();
            if (!(first == 1 || second == 1 || first == 0 || second == 0)) {
                JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                        textBundle.getString(TextBundleEnum.WARNING_UNICO_CARACTER_ATOMICAS.toString()) + "!", "",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                if (checkIsNumber(input)) {
                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                            textBundle.getString(TextBundleEnum.WARNING_NO_NUMEROS_ATOMICAS.toString()) + "!", "",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    if (tableTitles.size() != 0) {
                        char[] array = tableTitles.get(tableTitles.size() - 1).toCharArray();
                        if (input.charAt(0) == ')') {
                            if (array[array.length - 1] == '(') {
                                JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                        textBundle.getString(TextBundleEnum.WARNING_EXPRESION_NULA.toString()) + "!",
                                        "", JOptionPane.WARNING_MESSAGE);
                            } else {
                                if (checkIsNumber("" + array[array.length - 1])) {
                                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                            textBundle.getString(
                                                    TextBundleEnum.WARNING_OPERANDO_PARENTESIS.toString()) + "!", "",
                                            JOptionPane.WARNING_MESSAGE);
                                } else {
                                    input = tableTitles.get(tableTitles.size() - 1).concat(input);
                                    tableTitles.set(tableTitles.size() - 1, input);
                                }
                            }
                        } else {
                            if (array[array.length - 1] == '(') {//
                                input = tableTitles.get(tableTitles.size() - 1).concat(input);
                                tableTitles.set(tableTitles.size() - 1, input);
                            } else {
                                if (!checkIsNumber("" + input) && !checkIsNumber("" + array[array.length - 1])) {
                                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                            textBundle.getString(
                                                    TextBundleEnum.WARNING_PROPOSICIONES_SEGUIDAS.toString()) + "!", "",
                                            JOptionPane.WARNING_MESSAGE);
                                } else {
                                    if (input.contains("(")) {
                                        tableTitles.set(tableTitles.size() - 1, tableTitles.get(tableTitles.size() - 1).concat(getParenthesis(input)));
                                    }
                                    input = input.replace("(", "");
                                    if (!input.equals("")) {
                                        tableTitles.add(input);
                                    }
                                }
                            }
                        }
                    } else {
                        tableTitles.add(input);
                    }
                }
                addTableColumn(null);
            }
        }
        input = "";
    }

    private void resetearButtonActionPerformed() {
        displayTruthTable(truthTable.getArrayToComplete());
    }

    private void resetAll() {
        tableTitles = new ArrayList<String>();
        resetearButtonActionPerformed();
    }

    private void addTableColumn(Object[][] content) {
        if (content == null) {
            content = new Object[][]{};
        } else {
            content = stringsToLabels((String[][]) content);
        }
        table.setModel(new javax.swing.table.DefaultTableModel(
                content, tableTitles.toArray()
        ) {//this prevents the table being editable!

            public boolean isCellEditable(int row, int column) {
                if (getValueAt(row, column) != null) {
                    if (getValueAt(row, column).getClass().equals((new JLabel()).getClass())) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    return true;
                }
            }
        });

        table.getModel().addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                int row = e.getFirstRow();
                int column = e.getColumn();
                TableModel model = (TableModel) e.getSource();
                String data = (String)model.getValueAt(row, column);
                ((String [][])testExercise.getStudentsSolution())[row][column]=data;
            }
        });

        JLabel label;
        String current;
        String parenthesis;
        for (int j = 0; j < tableTitles.size(); j++) {
            label = new JLabel();
            label.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
            current = tableTitles.get(j).replace("(", "");
            current = current.replace(")", "");
            parenthesis = getParenthesis(tableTitles.get(j));
            table.getColumnModel().getColumn(j).setHeaderRenderer(new JComponentCellRenderer());
            setTableRenderer(new JComponentCellRenderer(), new DefaultTableCellRenderer(), j);
            label.setFont(new Font("Tahoma", 1, 16));
            if (current.equalsIgnoreCase("0")) {
                label.setText(parenthesis);
                if (isOpenParenthesisBeforeNegation(tableTitles.get(j))) {
                    label.setHorizontalTextPosition(SwingConstants.LEFT);
                }
                label.setIcon(Utiles.createImageIcon(URLEnum.getReference(URLEnum.NEGACION)));
                table.getColumnModel().getColumn(j).setHeaderValue(label);
            } else {
                if (current.equalsIgnoreCase("1")) {
                    label.setText(parenthesis);
                    label.setIcon(Utiles.createImageIcon(URLEnum.getReference(URLEnum.CONDICIONAL)));
                    table.getColumnModel().getColumn(j).setHeaderValue(label);
                } else {
                    if (current.equalsIgnoreCase("2")) {
                        label.setText(parenthesis);
                        label.setIcon(Utiles.createImageIcon(URLEnum.getReference(URLEnum.BICONDICIONAL)));
                        table.getColumnModel().getColumn(j).setHeaderValue(label);
                    } else {
                        if (current.equalsIgnoreCase("3")) {
                            label.setText(parenthesis);
                            label.setIcon(Utiles.createImageIcon(URLEnum.getReference(URLEnum.DISYUNCION_EXCLUSIVA)));
                            table.getColumnModel().getColumn(j).setHeaderValue(label);
                        } else {
                            if (current.equalsIgnoreCase("4")) {
                                label.setText(parenthesis);
                                label.setIcon(Utiles.createImageIcon(URLEnum.getReference(URLEnum.NEGACION_CONJUNTA)));
                                table.getColumnModel().getColumn(j).setHeaderValue(label);
                            } else {
                                if (current.equalsIgnoreCase("5")) {
                                    label.setText(parenthesis);
                                    label.setIcon(Utiles.createImageIcon(URLEnum.getReference(URLEnum.DISYUNCION_INCLUSIVA)));
                                    table.getColumnModel().getColumn(j).setHeaderValue(label);
                                } else {
                                    if (current.equalsIgnoreCase("6")) {
                                        label.setText(parenthesis);
                                        label.setIcon(Utiles.createImageIcon(URLEnum.getReference(URLEnum.INCOMPATIBILIDAD)));
                                        table.getColumnModel().getColumn(j).setHeaderValue(label);
                                    } else {
                                        if (current.equalsIgnoreCase("7")) {
                                            label.setText(parenthesis);
                                            label.setIcon(Utiles.createImageIcon(URLEnum.getReference(URLEnum.CONJUNCION)));
                                            table.getColumnModel().getColumn(j).setHeaderValue(label);
                                        } else {
                                            label.setText(" " + tableTitles.get(j));
                                            table.getColumnModel().getColumn(j).setHeaderValue(label);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            table.getTableHeader().revalidate();
        }
    }

    private Object[][] stringsToLabels(String[][] tableResult) {
        String[][]toComplete=truthTable.getArrayToComplete();
        Object[][] matrix = new Object[tableResult.length][tableResult[0].length];
        for (int j = 0; j < tableResult.length; j++) {
            for (int i = 0; i < tableResult[0].length; i++) {
                if (toComplete[j][i].equalsIgnoreCase("") || toComplete[j][i].replace(" ", "").equals("")) {
                    matrix[j][i] = tableResult[j][i];
                } else {
                    matrix[j][i] = new JLabel(tableResult[j][i]);
                }
            }
        }
//        for (int j = 0; j < tableResult.length; j++) {
//            for (int i = 0; i < tableResult[0].length; i++) {
//                if (tableResult[j][i].equalsIgnoreCase("") || tableResult[j][i].replace(" ", "").equals("")) {
//                    matrix[j][i] = null;
//                } else {
//                    matrix[j][i] = new JLabel(tableResult[j][i]);
//                }
//            }
//        }
        return matrix;
    }

    private void setTableRenderer(TableCellRenderer labelRenderer, TableCellRenderer stringRenderer, int column) {
        try {
            if (table.getValueAt(0, column) != null) {
                if (table.getValueAt(0, column).getClass().equals((new JLabel()).getClass())) {
                    table.getColumnModel().getColumn(column).setCellRenderer(labelRenderer);
                } else {
                    table.getColumnModel().getColumn(column).setCellRenderer(stringRenderer);
                }
            } else {
                table.getColumnModel().getColumn(column).setCellRenderer(stringRenderer);
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            table.getColumnModel().getColumn(column).setCellRenderer(labelRenderer);
        }
    }

    private boolean isOpenParenthesis(String parenthesis) {
        if (parenthesis.length() > 0) {
            return parenthesis.charAt(0) == '(';
        }
        return false;
    }

    private boolean isOpenParenthesisBeforeNegation(String expression) {
        return expression.indexOf("(") != -1 && expression.indexOf("(") < expression.indexOf("0");
    }

    private boolean checkIsNumber(String input) {
        char[] array = input.toCharArray();
        char character;
        for (int j = 0; j < array.length; j++) {
            character = array[j];
            if (character == '0' || character == '1' || character == '2' || character == '3' || character == '4'
                    || character == '5' || character == '6' || character == '7' || character == '8' ||
                    character == '9') {
                return true;
            }
        }
        return false;
    }

    //no considera la negacion
    private boolean checkIsOperand(String input) {
        char[] array = input.toCharArray();
        char character;
        for (int j = 0; j < array.length; j++) {
            character = array[j];
            if (character == '1' || character == '2' || character == '3' || character == '4' || character == '5' ||
                    character == '6' || character == '7') {
                return true;
            }
        }
        return false;
    }

    private String buildExpression() {
        int size = tableTitles.size();
        StringBuffer stringBuffer = new StringBuffer();
        for (int j = 0; j < size; j++) {
            stringBuffer.append(tableTitles.get(j));
        }
        return stringBuffer.toString();
    }

    private String getParenthesis(String current) {
        char parenthesisOpen = '(';
        char parenthesisClose = ')';
        char[] array = current.toCharArray();
        StringBuffer stringBuffer = new StringBuffer();
        for (int j = 0; j < array.length; j++) {
            if (array[j] == parenthesisOpen || array[j] == parenthesisClose) {
                stringBuffer.append("" + array[j]);
            }
        }
        return stringBuffer.toString();
    }

    /**
     * Muestra la tabla de verdad;
     */
    private void displayTruthTable(String[][] grid) {
        addTableColumn(grid);
    }

    private void getTableHeader(TruthTable truthTable) {
        String expression = truthTable.getExpression();
        StringBuffer buffer = new StringBuffer();
        char[] expressionArray = expression.toCharArray();
        for (int j = 0; j < expressionArray.length; j++) {
            if (checkIsNumber("" + expressionArray[j])) {
                if (!buffer.toString().equals("")) {
                    input = buffer.toString();
                    acceptButtonActionPerformed();
                    buffer = new StringBuffer();
                    performOperandAction("" + expressionArray[j]);
                }
            } else {
                buffer.append(expressionArray[j]);
            }
        }
        if (!buffer.toString().equals("")) {
            input = buffer.toString();
            acceptButtonActionPerformed();
        }
    }

    private void performOperandAction(String operandString) {
        int operand = Integer.parseInt(operandString);
        switch (operand) {
            case 0:
                negacionButtonActionPerformed();
                break;
            case 1:
                condicionalButtonActionPerformed();
                break;
            case 2:
                bicondicionalButtonActionPerformed();
                break;
            case 3:
                disyuncionExclusivaButtonActionPerformed();
                break;
            case 4:
                negacionConjuntaButtonActionPerformed();
                break;
            case 5:
                disyuncionInclusivaButtonActionPerformed();
                break;
            case 6:
                incompatibilidadButtonActionPerformed();
                break;
            case 7:
                conjuncionButtonActionPerformed();
                break;
        }
    }

    private JPanel createScoringPanel() {
        JPanel scoringPanel = new JPanel();
        scoringPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK),
                textBundle.getString(TextBundleEnum.PUNTAJE.toString())));
        scoringPanel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        scoringPanel.add(addsPoints, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        scoringPanel.add(addsPointsField, gridBagConstraints);
//        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridx = 2;
        scoringPanel.add(substractPoints, gridBagConstraints);
        gridBagConstraints.gridx = 3;
        scoringPanel.add(substractPointsField, gridBagConstraints);
        scoringPanel.setBackground(Color.WHITE);
        return scoringPanel;
    }

    public TestExcercise getExercise() throws ExerciseNotBuiltException, PunctuationZeroException {
        testExercise = new TestTruthTable();
        testExercise.setStudentsSolution(fromJTableToBooleanSolution(table));
        return testExercise;
    }

    public void setExercise(TestExcercise testExerciseData) {
        testExercise = testExerciseData;
        truthTable = (TruthTable) testExerciseData.getExcerciseData();
        resetAll();//todo revisar, se solapan metodos... 
        getTableHeader(truthTable);
        displayTruthTable((String[][]) testExercise.getStudentsSolution());
        addsPointsField.setText("" + testExerciseData.getCorrectScore());
        substractPointsField.setText("" + testExerciseData.getIncorrectScore());
    }

    public static String[][] fromJTableToBooleanSolution(JTable table) {//todo revisar necesidad de metodo estatico...
        TableModel model = table.getModel();
        int rows = model.getRowCount();
        int cols = model.getColumnCount();

        String[][] solution = new String[rows][cols];
        for (int j = 0; j < cols; j++) {
            for (int i = 0; i < rows; i++) {
                if (model.getValueAt(i, j).toString().equalsIgnoreCase("V")) {
                    solution[i][j] = "V";
                } else {
                    solution[i][j] = "F";
                }
            }
        }
        return solution;
    }
}
